import 'dart:io';

import 'package:bai_le_men_im/cmomon/global.dart';
import 'package:bai_le_men_im/models/user.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wildfire/flutter_wildfire.dart';
import 'package:image_picker/image_picker.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:photo_view/photo_view.dart';

class ModifyMyAvatar extends StatefulWidget {
  @override
  _ModifyMyAvatarState createState() => _ModifyMyAvatarState();
}

class _ModifyMyAvatarState extends State<ModifyMyAvatar> {
  /// 获取权限
  Future<bool> getPermission(
      List<PermissionGroup> _permissionGroups, String _errorStr) async {
    Map<PermissionGroup, PermissionStatus> permissions =
        await PermissionHandler().requestPermissions(_permissionGroups);
    List _permissions = List.generate(permissions.keys.length, (i) {
      return permissions[permissions.keys.toList()[i]] ==
          PermissionStatus.granted;
    });
    if (_permissions.every((_permission) {
      return _permission;
    })) {
      return true;
    } else {
      toast(_errorStr);
      return false;
    }
  }

  saveMyAvatarHandler(ImageSource source) async {
    File _image = await ImagePicker.pickImage(source: source);
    if (_image == null) {
      Navigator.of(context).pop();
    } else {
      try {
        var result = await FlutterWildfire.modifyMyInfoPortrait(_image.path);
        print(result);
      } catch (e) {
        var result =
            await FlutterWildfire.getUserInfo(Global.profile.user.uid, true);
        User user = User.fromJson(result);
        if (user.portrait == Global.profile.user.portrait) {
          toast('更新头像失败');
        } else {
          Global.profile.user = user;
          Navigator.of(context).pop();
        }
      }
    }
  }

  showMenu() async {
    return showCupertinoModalPopup<void>(
      context: context,
      builder: (BuildContext context) {
        return CupertinoActionSheet(
          actions: <Widget>[
            CupertinoActionSheetAction(
              child: Text('拍照'),
              onPressed: () async {
                Navigator.of(context).pop();
                if (await getPermission(
                    [PermissionGroup.camera, PermissionGroup.storage],
                    "获取权限失败")) {
                  try {
                    ImageSource source = ImageSource.camera;
                    await saveMyAvatarHandler(source);
                  } catch (e) {
                    print(e);
                    print('imagePicker error');
                  }
                }
              },
            ),
            CupertinoActionSheetAction(
              child: Text('从手机相册选择'),
              onPressed: () async {
                Navigator.of(context).pop();
                if (await getPermission(
                    [PermissionGroup.photos, PermissionGroup.storage],
                    "获取权限失败")) {
                  try {
                    ImageSource source = ImageSource.gallery;
                    await saveMyAvatarHandler(source);
                  } catch (e) {
                    print(e);
                    print('imagePicker error');
                  }
                } else {}
              },
            ),
          ],
          cancelButton: CupertinoActionSheetAction(
            isDefaultAction: true,
            child: Text('取消'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    String portrait = Global.profile.user.portrait;
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        elevation: 0.0,
        centerTitle: true,
        iconTheme: Theme.of(context).iconTheme.copyWith(color: Colors.white),
        title: Text(
          '个人头像',
          style: TextStyle(color: Colors.white),
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.more_horiz, color: Colors.white),
            onPressed: showMenu,
          )
        ],
        backgroundColor: Colors.transparent,
      ),
      body: (portrait == null || portrait.isEmpty)
          ? Container(
              child: Center(
                child: FlatButton(
                  color: Colors.greenAccent,
                  textColor: Colors.white,
                  onPressed: showMenu,
                  child: Text('点击开始设置头像'),
                ),
              ),
            )
          : PhotoView(imageProvider: NetworkImage(portrait)),
    );
  }
}
